<template>
  <div id="addScoringResultPage">
    <h1>编辑评分策略列表</h1>

    <div class="formWrapper">
      <h3>评分策略详情</h3>

      <el-form :model="form" ref="formRef" label-width="100px">
        <el-form-item label="评分结果 id" prop="id">
          <el-input :value="form.id" clearable disabled />
        </el-form-item>
        <el-form-item label="评分结果名称" prop="resultName">
          <el-input v-model="form.resultName" clearable placeholder="请输入评分结果名称" />
        </el-form-item>
        <el-form-item label="评分结果描述" prop="resultDesc">
          <el-input v-model="form.resultDesc" type="textarea" :rows="2" clearable placeholder="请输入评分结果描述" />
        </el-form-item>
        <el-form-item label="评分结果图片" prop="resultPicture">
          <PictureUploader v-model:image-url="form.resultPicture" :file-upload-type="FileUploadTypeEnum.SCORING_RESULT_PICTURE" />
        </el-form-item>
        <el-form-item label="评分结果属性" prop="resultProp" v-if="appVO?.appType === AppTypeEnum.QUESTION">
          <!-- <el-input v-model="form.resultProp" clearable multiple placeholder="请输入评分结果属性 (按回车分隔)" /> -->
          <el-select v-model="form.resultProp"
            clearable multiple filterable allow-create default-first-option
            :reserve-keyword="false"
            placeholder="请输入评分结果属性 (按回车分隔)">
            <!-- <el-option v-for="item in knowledge" :key="item.value" :label="item.label" :value="item.label"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item label="评分触发上限" prop="resultScoreRange" v-else>
          <el-input v-model="form.resultScoreRange" clearable placeholder="当多个评分结果被触发时, 分数最高的作为最终的评分结果" />
        </el-form-item>
      </el-form>

      <el-button type="info" plain size="default" class="submitButton" @click="router.back">
        返回
      </el-button>
      <el-button type="primary" size="default" @click="Object.assign(form, defaultFormData)">新增评分结果</el-button>
      <el-button type="primary" size="default" @click="doSubmit">{{ form.id ? "提交评分结果修改" : "提交新增评分结果" }}</el-button>
    </div>

    <div class="tableWrapper">
      <h3>评分策略列表</h3>

      <!-- 分页 -->
      <el-pagination @size-change="onSizeChange" @current-change="doSearch" v-model:currentPage="searchParams.current"
        :page-sizes="[5, 10, 15, 20]" :page-size="searchParams.pageSize" layout="total, sizes, prev, pager, next"
        :total="totalNum" background :pager-count="9" :disabled="isLoading">
      </el-pagination>

      <el-table :data="tableData" v-loading="isLoading">
        <el-table-column prop="id" label="评分结果 id" />
        <el-table-column prop="resultName" label="评分结果名称" />
        <el-table-column prop="resultDesc" label="评分结果描述" />
        <el-table-column prop="resultPicture" label="评分结果图片">
          <template #default="scope">
            <template v-if="scope.row.resultPicture">
              <img :src="scope.row.resultPicture" style="width: 64px; height: 64px;" />
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="resultProp" label="评分结果属性" v-if="appVO?.appType === AppTypeEnum.QUESTION" />
        <el-table-column prop="resultScoreRange" label="评分结果范围" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" type="primary" :icon="Edit" @click="handleEdit(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getAppVoByIdUsingGet } from '@/api/appController';
import { addScoringResultUsingPost, deleteScoringResultUsingDelete, editScoringResultUsingPost, listScoringResultVoByPageUsingPost, updateScoringResultUsingPost } from '@/api/scoringResultController';
import PictureUploader from '@/components/PictureUploader.vue';
import { AppTypeEnum, FileUploadTypeEnum, ResponseCodeEnum } from '@/enums';
import { Delete, Edit } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();

// 评分规则对应应用 id
const { appId } = defineProps(["appId"]);

// 应用信息
const appVO = ref<API.AppVO>();

// 默认表单数据
const defaultFormData = {
  id: undefined,
  resultDesc: '',
  resultName: '',
  resultPicture: '',
  resultProp: [],
  resultScoreRange: 0
};

// 当前正在编辑的评分结果
const form = ref<API.ScoringResultVO>({
  id: undefined,
  resultDesc: '',
  resultName: '',
  resultPicture: '',
  resultProp: [],
  resultScoreRange: 0
});

// 评分结果列表
const tableData = ref<API.ScoringResultVO[]>([]);

// 分页插件总页数
const totalNum = ref(0);

// 表格是否加载中
const isLoading = ref(false);

// 查询条件
const searchParams = ref<API.ScoringResultQueryRequest>({
  appId: appId,
  current: 1,
  pageSize: 10,
});

/**
 * 执行查询
 */
const doSearch = async () => {
  isLoading.value = true;

  const result = await listScoringResultVoByPageUsingPost(searchParams.value);

  if (result.data.code === ResponseCodeEnum.SUCCESS) {
    // 更新表单数据与总数
    tableData.value = result.data.data?.records || [];
    totalNum.value = Number(result.data.data?.total) || 0;
  } else {
    ElMessage.error("获取数据失败: " + result.data.message);
  }

  isLoading.value = false;
};

/**
 * 当一页的数据量改变时触发
 * @param pageSize 当前一页容量
 */
const onSizeChange = (pageSize: number) => {
  searchParams.value.pageSize = pageSize;
  searchParams.value.current = 1;
  doSearch();
}

// 首次挂载时请求数据
onMounted(async () => {
  // 获取应用信息
  const appResult = await getAppVoByIdUsingGet({
    id: appId
  })

  // 赋值给 appVO
  if (appResult.data.code === ResponseCodeEnum.SUCCESS && appResult.data.data) {
    appVO.value = appResult.data.data;
  } else {
    ElMessage.error("获取应用数据失败: " + appResult.data.message);
  }

  doSearch();
});

/**
 * 编辑评分结果
 * @param index 所在行号
 * @param row 所在行数据
 */
const handleEdit = (index: number, row: API.ScoringResultVO) => {
  form.value = row;
}

/**
 * 删除评分结果
 * @param index 所在行号
 * @param row 所在行数据
 */
const handleDelete = (index: number, row: API.ScoringResultVO) => {
  ElMessageBox.confirm(
    '此操作将删除该评分结果, 是否继续 ?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const result = await deleteScoringResultUsingDelete({
      id: row.id
    })

    if (result.data.code === ResponseCodeEnum.SUCCESS) {
      ElMessage.success(`成功删除 id = ${row.id} 的评分结果`);
      doSearch();
    } else {
      ElMessage.error("删除失败: " + result.data.message);
    }
  }).catch(() => { })
}

/**
 * 提交按钮
 */
const doSubmit = async () => {
  let result;
  const request: API.ScoringResultQueryRequest = {
    id: form.value.id ?? appId,
    ...form.value 
  }

  if (form.value.id) {
    // 已有 id, 更新评分结果
    result = await editScoringResultUsingPost(request);
  } else {
    result = await addScoringResultUsingPost(request);
  }

  if (result.data.code === ResponseCodeEnum.SUCCESS) {
    ElMessage.success(
      form.value.id ?
        `成功修改 id = ${form.value.id} 的评分结果` : `成功创建 id = ${result.data.data} 的评分结果`
    );
    // 重新进行一次查询
    doSearch();
  } else {
    ElMessage.error("修改失败: " + result.data.message);
  }

}
</script>

<style scoped lang="less">
#addScoringResultPage {
  padding: 20px;
  width: 80%;
  margin: 0 auto;

  .formWrapper {
    .el-button {
      width: 150px;
    }
  }
}
</style>